<?php
/**
 * Created by PhpStorm.
 * User: 丶晓
 * Date: 2017/11/27
 * Time: 17:07
 */

namespace app\api\service;


use app\api\model\DataModel;
use app\api\model\MiniappsModel;
use app\common\Base;
use GatewayWorker\Lib\Gateway;
use think\Config;
use think\Request;
use think\Session;

class SocketService
{
    public static function getToken($appid)
    {
        return empty($appid) ? 'appid lost!' : md5($appid . date('Ymd'));
    }

    public static function vailToken($appid, $token)
    {
        return $token == md5($appid . date('Ymd')) ? true : false;
    }

    public static function sendMessage($client_id, $message = '@heart')
    {
        if (empty($client_id)) {
            return false;
        }
        $time = 0;
        while (!Gateway::sendToClient($client_id, $message)) {
            $time++;
            if ($time > 3) {
                return false;
            }
            sleep(Config::get('socket.sleep'));
        }
        return true;
    }

    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        // 向当前client_id发送数据
        if (!Session::get('socketToken')) {
            Gateway::sendToClient($client_id, "@connect");
        }
        require_once __DIR__ . '/../../common/Base.php';
        $RES = Base::_requestPost('https://api.suyongw.com/socket/clientConnect',['client_id' => $client_id, 'client_ip' => Request::instance()->ip()]);
        if ($RES != 'Think for your Watch!') {
            Gateway::sendToClient($client_id, $RES);
        }

    }

    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {
        require_once __DIR__ . '/../../common/Base.php';
        $RES = Base::_requestPost('https://api.suyongw.com/socket/clientMessage', ['client_id' => $client_id, 'client_message' => $message]);
        if ($RES != 'Think for your Watch!') {
            Gateway::sendToClient($client_id, $RES);
        }
    }

    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id)
    {

        require_once __DIR__ . '/../../common/Base.php';
        $RES = Base::_requestPost('https://api.suyongw.com/socket/clientClose',['client_id' => $client_id]);
        if ($RES != 'Think for your Watch!') {
            Gateway::sendToClient($client_id, $RES);
        }

        // 下线Socket记录数据库
    }


}